package com.liu.upload;

import com.liu.utils.StreamUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author liuchengjie
 */
public class SocketFileUploadClient {
    public static void main(String[] args) throws IOException {
        String filePath = "/Users/liuchengjie/Pictures/真相是什么.png";
        //客户端连接服务端
        Socket socket = new Socket(InetAddress.getLocalHost(), 8888);
        //创建读取磁盘文件的输入流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filePath));
        //把文件转换成字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        //把文件写入到通道
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(socket.getOutputStream());
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.flush();
        socket.shutdownOutput();
        //接收服务端信息
        BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
        byte[] message = StreamUtils.streamToByteArray(in);
        System.out.println(new String(message));
        in.close();
        bufferedInputStream.close();
        bufferedOutputStream.close();
        socket.close();
    }
}
